package com.intsig.imageprocess;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;

import com.intsig.scanner.ScannerEngine;
import com.intsig.scanner.ScannerSDK;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * {@link ImageScannerActivity} 图片切边，增强，保存操作
 * 
 * @author Ben
 * 
 */
public class ISImageEnhanceHandler {

	private static final String TAG = "ISImageEnhanceHandler";
	
	/**
	 * 回调listener: 后台大图处理完成时回调，用于界面需要刷新图片时
	 * @author Ben
	 *
	 */
	public interface IsImageHandleFinishListener{
		/**
		 * 图片切边增强完成时回调
		 * @param pageId 处理完的图片id
		 */
		public void onImageHandleFinish(long pageId);
	}
	
	private Context mContext;
	private int mEngineContext;		// MainUiThread Context;
	/**
	 * ScanRecordControl instance to record scanning processing
	 */
	private ScanRecordControl mScanRecordControl;
	
	/**
	 * whether prepared for pre saving
	 */
	private boolean mPrepared = false;
	
	//原图，缩略图 img path
	private String mRawJpgPath;
	private String mThumbJpgPath;
	/**
	 * decode from {@link ISImageEnhanceHandler#mThumbJpgPath}
	 */
	private int mThumbStruct;
	/**
	 * int[width, height] of raw image
	 */
	private int[] mRawImageBounds;
	
	/**
	 * text rotation detect from thumb; values as 0, 90, 180, 270
	 */
	private int mTextRotation;
	
	/**
	 * temp path for storing raw scanner image 
	 */
	private String mTmpStorePath;
	/**
	 * path for final storing scanned jpg
	 */
	private String mJpgPath;
	/**
	 * when image scanning finish, whether need to call {@link ISImageEnhanceHandler#onSaveFinish()}
	 */
	private boolean mIsNeedSave;
	
	/**
	 * 当前识别
	 */
	private boolean mIsCurrTextRotationDetectedFail = false;
	
	private ArrayList<IsImageHandleFinishListener> mListeners;
	
	/**
	 * intent action, values like {@link CONSTANT#SCANNER_ACTION_NEW_PAGE}
	 */
	private String mAction;
	private long mPageId;
	private String mImageUUID;
	
	private boolean mIsThumbTrimed = false;	// 小图是否已经切过边了
	private boolean mIsThumbTriming = false;	// 小图是否正在切边
	
	private ImageStoreRequest mCurRequest;	// 当前正在处理的请求
	private ImageStoreRequest mFinishRequest;	// 已经完成的请求
	private ImageStoreRequest mRequest;	//待处理的请求
	
	/**
	 * 切边增强界面的handler
	 */
	private Handler mImageScanHandler;
	
	/**
	 * 当前图片增强处理的线程
	 */
	private Thread mStoreThread;
	
	//--------------singleton------------
	private static ISImageEnhanceHandler sInstance;
	ScannerSDK mScannerSDK ;
	/**
	 * 如果当前对象为空，创建新对象
	 * @param context
	 * @return
	 */
	public static ISImageEnhanceHandler newInstance(Context context, Handler handler,ScannerSDK mScannerSDK){
		sInstance = new ISImageEnhanceHandler(context, handler,mScannerSDK);
		
		return sInstance;
	}
	
	/**
	 * 获取当前的单例对象，如果没有创建过该对象，返回空
	 * @return
	 */
	public static ISImageEnhanceHandler getInstace(){
		return sInstance;
	}
	
	/**
	 * 将当前单例对象置为空
	 */
	public static void releaseInstace(){
		sInstance = null;
	}
	
	/**
	 * 当前后台是否正在处理图片
	 * @param context
	 * @return
	 */
	public static boolean isBackendRunning(Context context){
		boolean res = false;
//		ISImageEnhanceHandler handler = ISImageEnhanceHandler.getInstace();
//		if(handler != null && !handler.isRawHandleFinish()){	// 正在处理大图
//			Toast.makeText(context, R.string.a_global_msg_task_process, Toast.LENGTH_SHORT).show();
//			res = true;
//		}
		return res;
	}
	
	private ISImageEnhanceHandler(Context context, Handler handler,ScannerSDK mScannerSDK){
		mContext = context;
		mImageScanHandler = handler;
		mEngineContext = 0;
		this.mScannerSDK=mScannerSDK;
		mListeners = new ArrayList<ISImageEnhanceHandler.IsImageHandleFinishListener>();
		mScanRecordControl = ScanRecordControl.getInstance(context);
	}
	
	
	/**
	 * 是否可以开始预保存
	 * <p>must call this method before {@link ISImageEnhanceHandler#requestStoreImage(ImageStoreRequest)}
	 * @param prepare
	 */
	public void setPrepared(boolean prepare){
		mPrepared = prepare;
	}
	
	public ImageStoreRequest newRawRequest(){
		return new ImageStoreRequest();
	}
	
	/**
	 * 添加listener
	 * @param l
	 */
	public void addListener(IsImageHandleFinishListener l){
		if(l != null && !mListeners.contains(l)){
			mListeners.add(l);
			Log.d(TAG, "addListener " + l);
		}
	}
	/**
	 * 移除listener
	 * @param l
	 */
	public void removeListener(IsImageHandleFinishListener l){
		mListeners.remove(l);
	}
	
	public void setImagePath(String rawPath, String thumbPath){
		mRawJpgPath = rawPath;
		mThumbJpgPath = thumbPath;
		mScanRecordControl.setImageRawPath(rawPath);
	}
	
	public void setTmpStorePath(String tmpPath){
		mTmpStorePath = tmpPath;
	}
	
	public void decodeThumb(){
		mThumbStruct = decodeImageS(mThumbJpgPath);
	}
	
	/**
	 * 设置engine context
	 * @param enginecontext
	 */
	public void setEngineContext(int enginecontext){
		mEngineContext = enginecontext;
		Log.d(TAG, "setEngineContext = " + enginecontext);
	}
	
	/**
	 * 使用该context时，需要小心，确保不会造成多线程冲突；尽量只在Ui线程中使用该内存
	 * @return MainUiThread Context
	 */
	public int getEngineContext(){
		return mEngineContext;
	}
	
	/**
	 * 判断当前imageView选中的区域是否为有效的切边区域
	 * @param imageView
	 * @return
	 */
//	public boolean isCanTrim(ImageEditView imageView) {
//		if(mRawImageBounds == null){
//			mRawImageBounds = Util.getImageBound(mRawJpgPath);
//		}
//		int[] wh = mRawImageBounds;
//		int[] cropBounds = imageView.getRegion(false);
//		boolean res = ScannerUtils.checkCropBounds(mEngineContext, wh, cropBounds);
//		Log.d(TAG, "isCanTrim = " + res + ", bounds = " + Arrays.toString(cropBounds));
//		return res;
//	}
//	
	/**
	 * 使用thumb检测文字方向
	 * @return int[2] as [angle, success], angle values in {0, 90, 180, 270}; <br/>
	 * success != {@link AngleDetector#FAILED} means success
	 */
//	public int[] detectTextRotation(){
//		int[] res = new int[2];
//		if(!isLegalImageStruct(mThumbStruct)){
//			decodeThumb();
//		}
//		if(isLegalImageStruct(mThumbStruct)){
//			res = detectTextRotation(mThumbStruct);
//		}
//		mTextRotation = res[0];
//		return res;
//	}
	
	/**
	 * call {@link ScannerEngine#decodeImageS(String)} to decode image
	 * @param imgPath 
	 * @return imageStruct
	 */
	private int decodeImageS(String imgPath){
		Log.d(TAG, "decodeImageS beign: " + imgPath);
		long start = System.currentTimeMillis();
		int imageStruct = ScannerEngine.decodeImageS(imgPath);
		start = System.currentTimeMillis() - start;
		Log.d(TAG, "decodeImageS consume " + start);
		Log.d(TAG, "decodeImageS finished, memory address:" + imageStruct);
		if(!isLegalImageStruct(imageStruct)){
			Log.d(TAG, "decodeImageS fail: " + imageStruct + ", file exist = " + new File(imgPath).exists());
		}
		return imageStruct;
	}
	
	/**
	 * 检测文字方向
	 * @param imageS
	 * @return int[2] as [angle, success], angle values in {0, 90, 180, 270};  <br/>
	 * success != {@link AngleDetector#FAILED} means success
	 */
//	private int[] detectTextRotation(int imageS){
//		Log.d(TAG, "detectTextAngle beign " + imageS);
//		int[] res = new int[2];
//		long start = System.currentTimeMillis();
//		int textRotation = AngleDetector.detectTextAngle(imageS);
//		res[1] = textRotation == AngleDetector.FAILED ? AngleDetector.FAILED : 1;
//		if (textRotation == AngleDetector.FAILED) {
//			textRotation = Util.getImageRotation(mRawJpgPath);
//			Log.d(TAG, "detectTextAngle failed use image rotation = " + textRotation);
//		}
//		start = System.currentTimeMillis() - start;
//		Log.d(TAG, "detectTextAngle textRotation = " + textRotation + " consume " + start);
//		res[0] = textRotation;
//		return res;
//	}
	
	/**
	 * 检测原图的切边区域，自动增强模式；
	 * @param boundResult 切边区域值返回在该数组中， length >= 8； if [0] = -1 -> 找边失败
	 * @param isNamecardMode 是否是名片模式下的图片
	 * @return 该图片对应的自动增强模式
	 */
//	public int detectRawBoundAutoMode(float[] boundResult, boolean isNamecardMode){
//		int imageSturct = decodeImageS(mRawJpgPath);
//        // 原图宽高
//        if(mRawImageBounds == null){
//            mRawImageBounds = Util.getImageBound(mRawJpgPath);
//        }
//		int autoMode = -1;
//		if(ScannerUtils.isLegalImageStruct(imageSturct) && mRawImageBounds != null){
//			int result = -1;
//			int[] borders = new int[8];
//			Log.d(TAG, "detectImageS beign");
//			long start = System.currentTimeMillis();
//			if(isNamecardMode){
//				result = ScannerUtils.detectNamecardBound(mEngineContext, imageSturct, mRawImageBounds, borders);
//			}else{
//				// 使用UI线程的context；程序UI行为可以确保此时UI线程不会触发重复内存操作
//				result = ScannerUtils.detectImageS(mEngineContext, imageSturct, borders);
//				start = System.currentTimeMillis() - start;
//				Log.d(TAG, "detectImageS consume " + start +" region number = " + result);
//			}
//			if(result >= 0){	// 找到边
//				float[] bound = ScannerUtils.getScanBoundF(mRawImageBounds, borders, result);
//				for(int i = 0; i < bound.length; i++){
//					boundResult[i] = bound[i];
//				}
//			}else{
//				boundResult[0] = -1;
//			}
//			
//			Log.d(TAG, "detectColorImageMode beign： " + imageSturct);
//			start = System.currentTimeMillis();
//			autoMode = ScannerEngine.detectColorImageMode(mEngineContext, imageSturct);
//			start = System.currentTimeMillis() - start;
//			Log.d(TAG, "detectColorImageMode result = " + autoMode + ", consume " + start);
//			
//			// 检测文字方向统计，原图，缩略图的比较
////			int rotation = detectTextRotation(imageSturct);
////			if(mTextRotation == rotation){
////				Logger.print(Logger.EVENT_TEXT_ROTATION_DETECT_SAME);
////			}else{
////				Logger.print(Logger.EVENT_TEXT_ROTATION_DETECT_DIFF);
////			}
////			Log.d(TAG, "detectTextRotation thumb = " + mTextRotation + ", raw = " + rotation);
//			ScannerEngine.releaseImageS(imageSturct);
//		}else{
//			boundResult[0] = -1;	// 找切边失败
//		}
//		return autoMode;
//	}
	
	/**
	 * 增强bitmap
	 * @param source
	 * @param mode 增强模式
	 */
	public void enhangeImage(Bitmap source, int mode){
		long start = System.currentTimeMillis();
		Log.d(TAG, "enhangeImage mode " + mode);
		ScannerEngine.enhanceImage(mEngineContext, source, mode);
		Log.d(TAG, "enhangeImage cost time is " + (System.currentTimeMillis() - start));
	}
	
	/**
	 * 判断当前处理图片时使用的参数是否与request一致
	 * @param request
	 * @return
	 */
	public boolean isDirty(ImageStoreRequest request){
		boolean res = false;
		if(mRequest != null){
			res = request.equals(mRequest);
		}else if(mCurRequest != null){
			res = request.equals(mCurRequest);
		}else if(mFinishRequest != null){
			res = request.equals(mFinishRequest);
		}
		Log.d(TAG, "isDirty = " + !res);
		return !res;
	}
	
	
	/**
	 * 请求：处理原图
	 * @param request
	 */
/*	public void requestStoreImage(ImageStoreRequest request){
		if(!mPrepared){	// 没有prepared，不接受请求
			return;
		}
		if(mCurRequest == null){	// 当前没有正在处理
			mCurRequest = request;
			Log.d(TAG, "requestStoreImage set to mCurRequest");
		}else{	// TODO 是否需要比较与cur Request 不同
			mRequest = request;
			Log.d(TAG, "requestStoreImage set to mRequest");
		}
		// 开启线程
		if(mStoreThread == null){
			mStoreThread = new Thread(mScannerRunnable);
			mStoreThread.start();
		}
	}*/
	
	public boolean isRawHandleFinish(){
		return mStoreThread == null;
	}
	
	/**
	 * 异步请求：保存图片
	 * @param jpgPath jpg path
	 * @param action intent action，重新编辑/文档新增页/新文档
	 * @param pageId optional, 重新编辑时传入page id
	 * @param imageUID optional, 文档新增页/新文档 时传入图片sync id
	 * @return true if 当前预保存已完成，不需要等待后台处理
	 * @see ISImageEnhanceHandler#requestSaveFinalToSync(String)
	 */
//	public boolean requestSaveFinalTo(String jpgPath, String action, long pageId, String imageUID){
//		boolean res = false;
//		mJpgPath = jpgPath;
//		mAction = action;
//		mPageId = pageId;
//		mImageUUID = imageUID;
//		if(mStoreThread == null){
//			FileUtil.renameOneFile(mTmpStorePath, mJpgPath);
//			Log.d(TAG, "requestSaveFinalTo rename file from " + mTmpStorePath + " to " + jpgPath);
//			res = true;
//		}else{
//			mIsNeedSave = true;
//		}
//		Log.d(TAG, "requestSaveFinalTo:" + jpgPath + ", mIsNeedSave = " + mIsNeedSave);
//		return res;
//	}
	
	/**
	 * 同步请求：保存图片。 会阻塞当前线程
	 * @param jpgPath
	 */
//	public void requestSaveFinalToSync(String jpgPath){
//		mIsNeedSave = false;
//		mJpgPath = jpgPath;
//		while(mStoreThread != null){	// 等待保存操作完成
//			try {
//				Thread.sleep(100);
//			} catch (InterruptedException e) {
//				Util.LOGE(TAG, e);
//			}
//		}
//		FileUtil.renameOneFile(mTmpStorePath, mJpgPath);
//		Log.d(TAG, "requestSaveFinalTo:" + jpgPath);
//	}
	


	/**
	 * 保存过程中，图片解析失败；将图片设置为STATUS_QUEUE，使用批处理处理当前图片；
	 */
//	private void onSaveError(){
//		// 图片处理完成，更新数据库
//		if(CONSTANT.SCANNER_ACTION_NEW_PAGE.equals(mAction) || CONSTANT.SCANNER_ACTION_NEW_DOC.equals(mAction)){	// 新增图片
//			long pageId = 0;
//			boolean isDBcreated = false;
//			for(int i = 0; i < 10 && !isDBcreated; i++){	// 重试10次，等待数据库创建
//				Cursor c = mContext.getContentResolver().query(Image.CONTENT_URI, 
//						new String[]{Image._ID},
//						Image.SYNC_IMAGE_ID + "=?", new String[]{mImageUUID}, null);
//				if(c != null){
//					if(c.moveToFirst()){
//						pageId = c.getLong(0);
//						isDBcreated = true;
//					}
//					c.close();
//				}
//				if(isDBcreated){	// 数据库记录存在，更新values
//					ContentValues values = new ContentValues();
//					values.put(Image.STATUS, Image.STATUS_QUEUE);	//设为QUEUE,请求批处理service处理
//					int row = mContext.getContentResolver().update(ContentUris.withAppendedId(Image.CONTENT_URI, pageId), values, null, null);
//					Util.LOGE(TAG, "onSaveError NEW_PAGE set state to queue: " + pageId + " = " + row);
//				}else{
//					try {
//						Thread.sleep(1000);	// 每隔1s重试一次
//					} catch (InterruptedException e) {
//						Util.LOGE(TAG, e);
//					}
//					Util.LOGE(TAG, "onSaveError new page can't find image uuid " + mImageUUID);
//				}
//			}
//		}else if(CONSTANT.SCANNER_ACTION_REEDIT_PAGE.equals(mAction) || CONSTANT.SCANNER_ACTION_PAGE_RETAKE.equals(mAction)){
//			Util.LOGE(TAG, "onSaveError REEDIT/RETAKE " + mAction);
//			DBUtil.setPageStatus(mContext, mPageId, Image.STATUS_QUEUE);
//		}
//	}
//	
	/**
	 * 图片预处理成功，此时有保存到正式环境的请求，更新数据库等相关操作
	 */
//	private void onSaveFinish(){
//		// 图片处理完成，更新数据库
//		if(CONSTANT.SCANNER_ACTION_NEW_PAGE.equals(mAction) || CONSTANT.SCANNER_ACTION_NEW_DOC.equals(mAction) ||
//				Intent.ACTION_SEND.equals(mAction)){
//			long pageId = 0;
//			boolean isDBcreated = false;
//			String thum_path = null, jpgpath = null, rawPath = null;
//			long docId = 0, pageNum = -1;
//			for(int i = 0; i < 10 && !isDBcreated; i++){	// 重试10次，等待数据库记录创建
//				Cursor c = mContext.getContentResolver().query(Image.CONTENT_URI, 
//						new String[]{Image._ID, Image._DATA, Image.THUMB_DATA, Image.DOCUMENT_ID, Image.PAGE_NUM, Image.RAW_DATA},
//						Image.SYNC_IMAGE_ID + "=?", new String[]{mImageUUID}, null);
//				if(c != null){
//					if(c.moveToFirst()){
//						thum_path = c.getString(2);
//						jpgpath = c.getString(1);
//						pageId = c.getLong(0);
//						docId = c.getLong(3);
//						pageNum = c.getInt(4);
//						rawPath = c.getString(5);
//						isDBcreated = true;
//					}
//					c.close();
//				}
//				if(isDBcreated){
//					ContentValues values = new ContentValues();
//					values.put(Image.STATUS, Image.STATUS_NORMAL);	// value 设置为normal
//					String thumb = BitmapUtils.makeAndStoreThumb(mTmpStorePath); 	// 创建新的thumb
//					FileUtil.renameOneFile(mTmpStorePath, jpgpath);
//					FileUtil.renameOneFile(thumb, thum_path);	// 图片替换
//					if(!TextUtils.equals(mRawJpgPath, rawPath)){
//						FileUtil.deleteOneFile(mRawJpgPath);
//						Log.d(TAG, "delete decreapt raw page: " + mRawJpgPath);
//					}
//					BitmapLoaderUtil.markDirty(pageId);	// 更新图片
//					if(pageNum == 1){	// 第一页，更新doc thumb
//						DBUtil.updateDocThumb(mContext, docId, pageId);
//					}
//					// 更新界面
//					for(IsImageHandleFinishListener l : mListeners){
//						if(l != null){
//							l.onImageHandleFinish(pageId);
//						}
//					}
//					
//					boolean register=PreferenceHelper.isCopyScannedImage2Gallery(mContext);
//					if (register) {
//						String srcPath = jpgpath;
//						String path = SDStorageManager.getScannedGalleryImagePath(mContext, jpgpath);
//						AppUtil.copyThenRegister2Gallery(mContext, srcPath, path);
//						Log.d(TAG, "register image to gallery: " + path);
//					}
//					
//					Log.d(TAG, "NEW onSaveFinish rename file from " + mTmpStorePath + " to " + jpgpath);
//					int row = mContext.getContentResolver().update(ContentUris.withAppendedId(Image.CONTENT_URI, pageId), values, null, null);
//					Log.d(TAG, "finish image replace, set state to normal: " + pageId + " = " + row);
//					SyncUtil.requestSync(mContext);
//				}else{
//					try {
//						Thread.sleep(1000);
//					} catch (InterruptedException e) {
//						Util.LOGE(TAG, e);
//					}
//					Util.LOGE(TAG, "onSaveFinish new page can't find image uuid " + mImageUUID);
//				}
//			}
//			
//		}else if(CONSTANT.SCANNER_ACTION_REEDIT_PAGE.equals(mAction) || CONSTANT.SCANNER_ACTION_PAGE_RETAKE.equals(mAction)){
//			FileUtil.renameOneFile(mTmpStorePath, mJpgPath);	// 重新编辑，图片替换，state=STATUS_NORMAL；具体操作在imagepageFragment 中完成
//			Log.d(TAG, "REEDIT onSaveFinish rename file from " + mTmpStorePath + " to " + mJpgPath);
//			DBUtil.setPageStatus(mContext, mPageId, Image.STATUS_NORMAL);
//		}
//		
//		
//	}
	
	/**
	 * 用户重新操作，放弃切边结果
	 */
//	public void restoreThumb(){
//		if(ScannerUtils.isLegalImageStruct(mThumbStruct)){
//			ScannerEngine.releaseImageS(mThumbStruct);
//		}
//		mThumbStruct = decodeImageS(mThumbJpgPath);
//	}
	
	public static boolean isLegalImageStruct(int imageStruct){
		return imageStruct>0;
}
	/**
	 * 缩略图切边
	 * @param bounds
	 */
	public void trimThumb(int bounds[]){
		// 已经做过切边，图脏了，需要重新加载
		Log.d(TAG, "trimThumb beign");
		mIsThumbTriming = true;
		long start = System.currentTimeMillis();
//		if(mIsThumbTrimed && ScannerUtils.isLegalImageStruct(mThumbStruct)){
//			ScannerEngine.releaseImageS(mThumbStruct);
//			mIsThumbTrimed = false;
//			mThumbStruct = 0;
//		}
		if(!isLegalImageStruct(mThumbStruct)){	// 是否需要重新加载图片
			mThumbStruct = decodeImageS(mThumbJpgPath);
		}
		if(isLegalImageStruct(mThumbStruct)){	// 切边
			mScanRecordControl.setCurrentScanStep(ScanRecordControl.TRIM_THUMB_STEP);
			mScanRecordControl.setTrimmedImageBorder(null, bounds);
			mScanRecordControl.setImageRawPath(mThumbJpgPath);
			try{
				boolean result = mScannerSDK.trimImage(mEngineContext, mThumbStruct, bounds,ImageScannerActivity.TRIM_IMAGE_MAXSIDE);
				Log.d(TAG, "trimThumb result " + result + ", " + Arrays.toString(bounds));
			}catch (RuntimeException e){
				Log.d(TAG, e.getMessage());
			}
			mIsThumbTrimed = true;
		}else{
			Log.d(TAG, "trimThumb decode thumb struct fail " + mThumbStruct);
		}
		start = System.currentTimeMillis() - start;
		mIsThumbTriming = false;
		Log.d(TAG, "trimThumb consume " + start);
	}
	
	/**
	 * 小图切边增强处理后，保存到savePath中
	 * @param request request param
	 * @param savePath 目标保存路径
	 */
//	public void storeThumbToFile(ImageStoreRequest request, String savePath){
////		if(!ScannerUtils.isLegalImageStruct(mThumbStruct)){
////			mThumbStruct = decodeImageS(mThumbJpgPath);
////		}
//		Log.d(TAG, "storeThumbToFile start ");
////		while(mIsThumbTriming){	// 在3.4中，小图切边已经提前完成了，这个case不会进入
////			//do nothing
////		}
//		
//		if(ScannerUtils.isLegalImageStruct(mThumbStruct)){
//			long start, end, dur;
//			int result;
//			long cur = System.currentTimeMillis();
////			Log.d(TAG, "trimImageS beign");	// 切边
////			start = System.currentTimeMillis();
////			result = ScannerEngine.trimImageS(mEngineContext, mThumbStruct, request.bounds);
////			start = System.currentTimeMillis() - start;
////			Log.d(TAG, "trimImageS consume " + start);
////			Log.d(TAG, "trimImageS result " + result);
//			
//			if(request.enhanceMode > 0){
//				start = System.currentTimeMillis();	// 增强
//				result = ScannerEngine.enhanceImageS(mEngineContext, mThumbStruct, request.enhanceMode);
//				end = System.currentTimeMillis() - start;
//				Log.d(TAG, "Thumb enhanceImageS consume " + end + " result " + result);
//			}else{
//				Log.d(TAG, "Thumb enhanceImageS skip with enhance mode = " + request.enhanceMode);
//			}
//			
//			if (request.rotation != 0) {	// 旋转
//				start = System.currentTimeMillis();
//				Log.d(TAG, "Thumb rotateAndScaleImageS begin");
//				result = ScannerEngine.rotateAndScaleImageS(mThumbStruct, request.rotation, 1.0f);
//				Log.d(TAG, "Thumb rotateAndScaleImageS ok mRotation = " + request.rotation + ", result = " + result);
//				end = System.currentTimeMillis();
//				dur = end - start;
//				Log.d(TAG, "Thumb rotate image file consume:" + dur + " ms");
//			}
//			
//			if (request.brightness != 50 || request.contrast != 50 || request.detail != 100) {	// 后期
//				start = System.currentTimeMillis();
//				Log.d(TAG, "Thumb adjustImageS begin");
//				result = ScannerEngine.adjustImageS(mEngineContext, mThumbStruct, request.brightness - 50, request.contrast - 50, request.detail);
//				end = System.currentTimeMillis();
//				dur = end - start;
//				Log.d(TAG, "Thumb adjust image file consume:" + dur + " ms result = " + result);
//			}
//			
//			start = System.currentTimeMillis();
//			Log.d(TAG, "Thumb encodeImageS begin to " + savePath);
//			result = ScannerEngine.encodeImageS(mThumbStruct, savePath, Const.IMAGE_QUALITY);// 保存
//			end = System.currentTimeMillis() - start;
//			Log.d(TAG, "Thumb encodeImageS result " + result+" consume " + end +" total consume " + (System.currentTimeMillis() - cur));
//		}else{
//			// scanner 引擎解析图片失败，复制thumb到savepath
//			boolean res = FileUtil.copyFile(mThumbJpgPath, savePath);
//			Util.LOGE(TAG, "storeThumbToFile decode thumb fail, copy file: " + res);
//		}
//		
//	}
//	
//	/**
//	 * 增强操作
//	 */
//	private Runnable mScannerRunnable = new Runnable() {
//		
//		@Override
//		public void run() {
//			long start, end, dur;
//			int result;
//			long cur;
//			String savePath = null;
//			mScanRecordControl.setImageRawPath(mRawJpgPath);
//			mScanRecordControl.setCurrentScanStep(ScanRecordControl.INIT_CONTEXT_STEP);
//			int engineContext = ScannerEngine.initThreadContext();	// 分配一块新的内存
//			int retryTime = 0;
//			while(mCurRequest != null){	// 如果当前有请求
//				Log.d(TAG, "StoreRunnable start " + mCurRequest + ", engineContext = " + engineContext);
//				cur = System.currentTimeMillis();
//				mScanRecordControl.setCurrentScanStep(ScanRecordControl.DECODE_IMAGE_STEP);
//				int mImageStruct = decodeImageS(mRawJpgPath);	// decode 图片
//				
//				if(!ScannerUtils.isLegalImageStruct(mImageStruct)){	// 图片解析失败
//					Util.LOGE(TAG, "StoreRunnable decodeImageS fail: " + engineContext);
//					if(retryTime < 1){	// 重试2次
//						// 解析失败
//						retryTime ++;
//						try {
//							Thread.sleep(1000);	// 每隔1s重试一次
//						} catch (InterruptedException e) {
//							Util.LOGE(TAG, e);
//						}
//					}else{	// 4次后图片还是失败，关闭本次请求
//						mStoreThread = null;	
//						if(mIsNeedSave){
//							mIsNeedSave = false;
//							onSaveError();
//						}
//						break;
//					}
//					continue;
//				}
//				
//				if(checkHasNewRequest()){
//					mScanRecordControl.setCurrentScanStep(ScanRecordControl.RELEASE_IMAGE_STEP);
//					ScannerEngine.releaseImageS(mImageStruct);
//					continue;
//				}
//				
////				mRawImageBounds = util.
//				if(mCurRequest.bounds != null){
//					if(mRawImageBounds == null || mRawImageBounds[0] == 0){
//						mRawImageBounds = Util.getImageBound(mRawJpgPath);
//					}
//					mScanRecordControl.setTrimmedImageBorder(mRawImageBounds, mCurRequest.bounds);
//					if(ScannerUtils.isNeedTrim(mCurRequest.bounds, mRawImageBounds)){
//						Log.d(TAG, "trimImageS beign: " + Arrays.toString(mCurRequest.bounds));
//						start = System.currentTimeMillis();
//						mScanRecordControl.setCurrentScanStep(ScanRecordControl.TRIM_IMAGE_STEP);
//						result = ScannerUtils.trimImageS(engineContext, mImageStruct, mCurRequest.bounds);
//						start = System.currentTimeMillis() - start;
//						Log.d(TAG, "trimImageS consume " + start+" result " + result);
//					}
//				}
//				//------------------
//				
//				
//				
//				
//				if(checkHasNewRequest()){
//					mScanRecordControl.setCurrentScanStep(ScanRecordControl.RELEASE_IMAGE_STEP);
//					ScannerEngine.releaseImageS(mImageStruct);
//					continue;
//				}
//				
//				if(mCurRequest.enhanceMode > 0){
//					start = System.currentTimeMillis();
//					mScanRecordControl.setCurrentScanStep(ScanRecordControl.ENHANCE_IMAGE_STEP);
//					mScanRecordControl.setImageEnhanceMode(mCurRequest.enhanceMode);
//					result = ScannerEngine.enhanceImageS(engineContext, mImageStruct, mCurRequest.enhanceMode);
//					end = System.currentTimeMillis() - start;
//					Log.d(TAG, "enhanceImageS consume " + end+" result " + result);
//					if(checkHasNewRequest()){
//						mScanRecordControl.setCurrentScanStep(ScanRecordControl.RELEASE_IMAGE_STEP);
//						ScannerEngine.releaseImageS(mImageStruct);
//						continue;
//					}
//				}else{
//					Log.d(TAG, "enhanceImageS skip with enhance mode = " + mCurRequest.enhanceMode);
//				}
//				
//				
//				if (mCurRequest.rotation != 0) {
//					start = System.currentTimeMillis();
//					Log.d(TAG, "rotateAndScaleImageS begin");
//					mScanRecordControl.setCurrentScanStep(ScanRecordControl.ROTATE_SCALE_IMAGE_STEP);
//					result = ScannerEngine.rotateAndScaleImageS(mImageStruct, mCurRequest.rotation, 1.0f);
//					Log.d(TAG, "rotateAndScaleImageS ok mRotation = " + mCurRequest.rotation + ", result = " + result);
//					end = System.currentTimeMillis();
//					dur = end - start;
//					Log.d(TAG, "rotate image file consume:" + dur + " ms");
//					if(checkHasNewRequest()){
//						mScanRecordControl.setCurrentScanStep(ScanRecordControl.RELEASE_IMAGE_STEP);
//						ScannerEngine.releaseImageS(mImageStruct);
//						continue;
//					}
//				}
//				
//				if (mCurRequest.brightness != 50 || mCurRequest.contrast != 50 || mCurRequest.detail != 100) {
//					start = System.currentTimeMillis();
//					Log.d(TAG, "adjustImageS begin");
//					mScanRecordControl.setImageBrightDetailContrastIndexs(mCurRequest.brightness - 50, mCurRequest.detail, mCurRequest.contrast - 50);
//					mScanRecordControl.setCurrentScanStep(ScanRecordControl.ADJUST_IMAGE_STEP);
//					result = ScannerEngine.adjustImageS(engineContext, mImageStruct, mCurRequest.brightness - 50, mCurRequest.contrast - 50, mCurRequest.detail);
//					end = System.currentTimeMillis();
//					dur = end - start;
//					Log.d(TAG, "adjust image file consume:" + dur + " ms result = " + result);
//					if(checkHasNewRequest()){
//						mScanRecordControl.setCurrentScanStep(ScanRecordControl.RELEASE_IMAGE_STEP);
//						ScannerEngine.releaseImageS(mImageStruct);
//						continue;
//					}
//				}
//				
//				savePath = mTmpStorePath;
//				start = System.currentTimeMillis();
//				Log.d(TAG, "encodeImageS begin to " + savePath);
//				mScanRecordControl.setCurrentScanStep(ScanRecordControl.ENCODE_IMAGE_STEP);
//				result = ScannerEngine.encodeImageS(mImageStruct, savePath, Const.IMAGE_QUALITY_NEW);// 80
//				end = System.currentTimeMillis() - start;
//				Log.d(TAG, "encodeImageS result " + result +" consume " + end + " total consume " + (System.currentTimeMillis() - cur));
//				mFinishRequest = mCurRequest;
//				mCurRequest = null;
//				checkHasNewRequest();
//			}// end of while
//			Log.d(TAG, "destroyThreadContext: " + engineContext);
//			if(engineContext != 0){
//				mScanRecordControl.setCurrentScanStep(ScanRecordControl.DESTROY_CONTEXT_STEP);
//				ScannerEngine.destroyThreadContext(engineContext);
//				mScanRecordControl.setImageRawPath("");
//			}else{
//				Util.LOGE(TAG, "engineContext is illegal");
//			}
//			if(mImageScanHandler != null){
//				mImageScanHandler.obtainMessage(ImageScannerActivity.MSG_BACK_SCAN_FINISH).sendToTarget();
//			}
//			mStoreThread = null;
//			if(mIsNeedSave){
//				onSaveFinish();
////				if(!mJpgPath.equals(savePath)){
////					FileUtil.renameOneFile(savePath, mJpgPath);
////					Log.d(TAG, "renameOneFile to mJpgPath: " + mJpgPath);
////				}
//				mIsNeedSave = false;
//			}
//			ISImageEnhanceHandler.releaseInstace();	// 大图切边完成，释放静态对象
//		}
//	};
	
	/**
	 * Request for Image Handle
	 * @author Ben
	 *
	 */
	public class ImageStoreRequest{
		public int[] bounds;
		public int rotation;
		public int enhanceMode;
		public int brightness;
		public int detail;
		public int contrast;
//		public String path;
		
		@Override
		public boolean equals(Object o) {
			boolean res = false;
			if(o instanceof ImageStoreRequest){
				ImageStoreRequest other = (ImageStoreRequest)o;
				if(bounds != null && other.bounds != null){
					for(int i = 0; i < bounds.length; i++){
						if(bounds[i] != other.bounds[i]){
							return res;
						}
					}
				}else if(bounds == null && other.bounds == null){
					
				}else{	// 两个bounds 一个null，另一个不是null
					return res;
				}
				
				res = rotation == other.rotation && enhanceMode == other.enhanceMode &&
						brightness == other.brightness && detail == other.detail &&
						contrast == other.contrast;
			}
			return res;
		}
		
		@Override
		public String toString() {
			return bounds + ", rotation = " + rotation + ", mode = " + enhanceMode + ", " +
					"brightness = " + brightness + ", detail = " + detail + ", contrast = " + contrast;
		}
	}
	
	/**
	 * 检查当前是否有新的图片保存请求
	 * @return
	 */
	private boolean checkHasNewRequest(){
		boolean res = false;
		if(mRequest != null){	// only check mRequest
			if(mCurRequest != null){	// 当前正在处理，与curRequest比较
				if(!mRequest.equals(mCurRequest)){
					mCurRequest = mRequest;
					res = true;
				}
			}else if(mFinishRequest != null && !mRequest.equals(mFinishRequest)){	// 当前处理完成，与finish request 比较
				mCurRequest = mRequest;
				res = true;
			}
			mRequest = null;
		}
		return res;
	}
	
}
